<template>
  <epgis-nav-container title="个人信息">
     <template #right>
      <div @click="openPreview"  class="layoutHorizontal" style="align-items: center;">
        <span style="font-size: 14px; ">预览</span>
      </div>
    </template>
    <template #container>
      <div style= "height: 100%; background: #f5f6f9;" class="layoutVerticle">
        <div style="padding: 12px 12px 12px 22px ; background: white" class="layoutHorizontal verticleCenter">
          <span style="">完整度</span>
          <van-progress :percentage="userInfo['dataRate']" style="flex: 1 1 auto; margin-left: 6px;"/>
        </div>
        
        <div  ref="personInformationScroll" style= "padding-left: 12px;padding-right: 12px; padding-bottom: 12px; overflow-y: scroll;" class="layoutVerticle">
          
          <div class="layoutVerticle shapeWhiteRadio layoutHead" style="">
            <div class="layoutHorizontal verticleCenter">
              <span class="spanItemTitle" >头像</span>
            </div>
            <div class="layoutHorizontal layoutCenter" style="margin-bottom: 34px;">
              <img :src="userInfo['headPictureUrl']" @click="selectFile(PictureEnum.HEAD)" style="width: 80px;height: 80px;border-radius: 50px;box-shadow: 0 0 0 1px white;"/>
            </div>
            
          </div>

          <div class="layoutVerticle shapeWhiteRadio" style="margin-top: -10px; position: relative;">
            <div style="height: 30px; background: linear-gradient(to top, rgba(255, 255, 255, 0.8), rgba(255, 255, 255, 0));  position: absolute; margin-top: -30px;left: 0px;right: 0px;">
            </div>
            <div class="layoutHorizontal verticleCenter">
              <span class="spanItemTitle" style="margin-top: -3px;margin-bottom: 7px;" >生活中的照片</span>
            </div>
            <div class="layoutHorizontal" style="align-items: center;">
              <div class="layoutPersonPhoto" style="">
                <div v-if="!userInfo['smilePicture']"  @click="selectFile(PictureEnum.SMILE)"  class="layoutVerticle layoutCenter layoutPersonDiv imgPersonPhoto">
                  <img src="@/assets/icon/home/attach.png"  style="height: 16px;"/>
                  <span class="spanPersonPhoto" >笑起来的样子</span>
                </div>
                <img v-if="userInfo['smilePicture']"  @click="showPicture(userInfo['smilePicture'])" :src="userInfo['smilePicture']"   class="imgPersonPhoto"/>
                <img v-if="userInfo['smilePicture']"  @click="deleteFile(PictureEnum.SMILE)" src="@/assets/icon/mine/delete.png"  class="imgDelete" />
              </div>
              <div  class="layoutPersonPhoto" style=" margin-left: 10px; ">
                <div v-if="!userInfo['lifePicture']"  @click="selectFile(PictureEnum.LIFE)"  class="layoutVerticle layoutCenter layoutPersonDiv imgPersonPhoto">
                  <img src="@/assets/icon/home/attach.png"  style="height: 16px;"/>
                  <span class="spanPersonPhoto" >生活中的样子</span>
                </div>
                <img v-if="userInfo['lifePicture']"  @click="showPicture(userInfo['lifePicture'])" :src="userInfo['lifePicture']"   class="imgPersonPhoto"/>
                <img v-if="userInfo['lifePicture']"  @click="deleteFile(PictureEnum.LIFE)" src="@/assets/icon/mine/delete.png"  class="imgDelete" />
              </div>
              <div class="layoutPersonPhoto" style="margin-left: 10px; ">
                <div v-if="!userInfo['tripPicture']"  @click="selectFile(PictureEnum.TRIP)"  class="layoutVerticle layoutCenter layoutPersonDiv imgPersonPhoto">
                  <img src="@/assets/icon/home/attach.png"  style="height: 16px;"/>
                  <span class="spanPersonPhoto" >得意的旅行照</span>
                </div>
                <img v-if="userInfo['tripPicture']"  @click="showPicture(userInfo['tripPicture'])" :src="userInfo['tripPicture']"   class="imgPersonPhoto"/>
                <img v-if="userInfo['tripPicture']"  @click="deleteFile(PictureEnum.TRIP)" src="@/assets/icon/mine/delete.png"  class="imgDelete" />
              </div>
            </div>
            <div class="layoutHorizontal" style="align-items: center; margin-top: 10px;">
              <div class="layoutPersonPhoto" style="">
                <div v-if="!userInfo['seriousPicture']"  @click="selectFile(PictureEnum.SERIOUS)"  class="layoutVerticle layoutCenter layoutPersonDiv imgPersonPhoto">
                  <img src="@/assets/icon/home/attach.png"  style="height: 16px;"/>
                  <span class="spanPersonPhoto" >得意的旅行照</span>
                </div>
                <img v-if="userInfo['seriousPicture']"  @click="showPicture(userInfo['seriousPicture'])" :src="userInfo['seriousPicture']"   class="imgPersonPhoto"/>
                <img v-if="userInfo['seriousPicture']"  @click="deleteFile(PictureEnum.SERIOUS)" src="@/assets/icon/mine/delete.png"  class="imgDelete" />
              </div>
              <div class="layoutPersonPhoto" style=" margin-left: 10px; ">
                <div v-if="!userInfo['talentPicture']"  @click="selectFile(PictureEnum.TALENT)"  class="layoutVerticle layoutCenter layoutPersonDiv imgPersonPhoto">
                  <img src="@/assets/icon/home/attach.png"  style="height: 16px;"/>
                  <span class="spanPersonPhoto" >得意的旅行照</span>
                </div>
                <img v-if="userInfo['talentPicture']"  @click="showPicture(userInfo['talentPicture'])" :src="userInfo['talentPicture']"   class="imgPersonPhoto"/>
                <img v-if="userInfo['talentPicture']"  @click="deleteFile(PictureEnum.TALENT)" src="@/assets/icon/mine/delete.png"  class="imgDelete" />
              </div>
              <div class="layoutPersonPhoto" style="margin-left: 10px; ">
                <div v-if="!userInfo['petPicture']"  @click="selectFile(PictureEnum.PET)"  class="layoutVerticle layoutCenter layoutPersonDiv imgPersonPhoto">
                  <img src="@/assets/icon/home/attach.png"  style="height: 16px;"/>
                  <span class="spanPersonPhoto" >得意的旅行照</span>
                </div>
                <img v-if="userInfo['petPicture']"  @click="showPicture(userInfo['petPicture'])" :src="userInfo['petPicture']"   class="imgPersonPhoto"/>
                <img v-if="userInfo['petPicture']"  @click="deleteFile(PictureEnum.PET)" src="@/assets/icon/mine/delete.png"  class="imgDelete" />
              </div>
            </div>
          </div>

          <div class="layoutVerticle shapeWhiteRadio">
            <div class="layoutHorizontal verticleCenter">
              <span class="spanItemTitle" >基础资料</span>
              <span @click="baseInformation" class="spanEdit" >编辑</span>
            </div>
            <div class="layoutHorizontal verticleCenter layoutItemText" >
              <span class="" >{{userInfo['username'] || userInfo['mobile']}}</span>
              <img v-if="userInfo['sex'] == SexEnum['SEX_BOY']" src="@/assets/icon/mine/boy.png"  style="height: 20px; margin-left: 6px;"/>
              <img v-if="userInfo['sex'] == SexEnum['SEX_GIRL']" src="@/assets/icon/mine/girl.png"  style="height: 20px; margin-left: 6px;"/>
            </div>
            <div class="layoutHorizontal verticleCenter layoutItemText" >
              <img src="@/assets/icon/home/height.png"  style="height: 16px; margin-right: 6px;"/>
              <span style="margin-left: 6px;" >{{userInfo['age']}}</span>
              <span style="margin-left: 6px;" >{{userInfo['height']}}</span>
              <span style="margin-left: 6px;" >{{userInfo['constellation']}}</span>
            </div>
            
            <div class="layoutHorizontal verticleCenter layoutItemText" >
              <img src="@/assets/icon/home/live.png"  style="height: 16px; margin-right: 6px;"/>
              <span style="margin-left: 6px;" >现居</span>
              <span style="margin-left: 6px;" >{{userInfo['liveCityName']}}</span>
            </div>
            <div class="layoutHorizontal verticleCenter layoutItemText" >
              <img src="@/assets/icon/home/workIndustry.png"  style="height: 16px; margin-right: 6px;"/>
              <span style="margin-left: 6px;" >{{userInfo['workIndustryName']}}</span>
            </div>
            <van-divider style="margin: 14px 0 0 0;"/>
            <van-cell title="家乡"   :value="userInfo['homeTownName']"    style="">
            </van-cell >
            <van-cell title="婚姻状况" :value="userInfo['maritalStatusName']"   style="">
            </van-cell >
          </div>

          <div class="layoutVerticle shapeWhiteRadio">
            <div class="layoutHorizontal verticleCenter">
              <span class="spanItemTitle" >自我介绍</span>
              <span @click="editIntroduction" class="spanEdit" >编辑</span>
            </div>
            <div class="layoutHorizontal verticleCenter layoutItemText" >
              <span class="" style="white-space: pre-line;">{{userInfo['selfDescription']}}</span>
            </div>
          </div>

          <div class="layoutVerticle shapeWhiteRadio">
            <div class="layoutHorizontal verticleCenter">
              <span class="spanItemTitle" >什么样的ta会吸引你</span>
              <span @click="editPartner" class="spanEdit" >编辑</span>
            </div>
            <div class="layoutHorizontal verticleCenter layoutItemText" >
              <span class="" style="white-space: pre-line;" >{{userInfo['partnerDescription']}}</span>
            </div>
          </div>

          <div class="layoutVerticle shapeWhiteRadio">
            <div class="layoutHorizontal verticleCenter">
              <span  class="spanItemTitle" >你觉得最浪漫的事情</span>
              <span @click="editRomantic" class="spanEdit" >编辑</span>
            </div>
            <div class="layoutHorizontal verticleCenter layoutItemText" >
              <span class="" style="white-space: pre-line;">{{userInfo['romanticThing']}}</span>
            </div>
          </div>
          
        </div>

        
        <input 
          :type="'file'"
          :accept="acceptFile"
          @change="fileChange"
          style="display: none"
          ref="file" />
      </div>
    </template>
  </epgis-nav-container>
</template>

<script>
import { Http, Uploader } from "@/common/HttpClient";
import { Toast, Notify } from "vant";
import { SexEnum, MaritalStatusEnum, EmotionStatusEnum, PictureEnum} from "@/views/mine/enums/PersonInformationEnum";
import { areaList } from "@/assets/arealist/Area.js"
import { getHeightArray , MaritalStatusArray , EmotionStatusArray, EducationLevelArray, WorkIndustryArray, YearlySalaryArray} from "@/views/mine/constants/PersonInformationConstants";
import { fileUploader } from "@/common/fileUploader";
import {ImagePreview} from "vant";

export default {
  components: {},
  data() {
    return {
      recommentSex:'',
      userInfo:{
        dataRate:0,
        username:'',
        liveCity:'',
        liveCityName:'',
        homeTownName:'',
        mobile:'',
        platformId:'',
        headPictureUrl: require('@/assets/icon/mine/cat.png'),
      },
      SexEnum:SexEnum,
      PictureEnum:PictureEnum,
      areaList:areaList,
      acceptFile:".jpg,.png",
      fileType:'',
    };
  },

  created(){
    this.requestUserInfo();
  },

  mounted() {
    this.$nextTick(() => {
      if(this.$refs.personInformationScroll){
        this.$refs.personInformationScroll.addEventListener('scroll', this.scrollEvent)
      }
    });
    this.handleMessage = (data) => {
      this.requestUserInfo();
    }
    // this.$bus.$off(['refreshUserInfo'])
    this.$bus.$on('refreshUserInfo', this.handleMessage);
  },
  destroyed() {
  },
  activated() {
    var personInformationScrollTopValue = sessionStorage.getItem("personInformationScrollTopValue");
    if(personInformationScrollTopValue && this.$refs.personInformationScroll){
      this.$refs.personInformationScroll.scrollTop = personInformationScrollTopValue
    }
  },
  beforeDestroy() {
    this.$bus.$off('refreshUserInfo', this.handleMessage);
    sessionStorage.removeItem("personInformationScrollTopValue");
    if(this.$refs.personInformationScroll){
      this.$refs.personInformationScroll.removeEventListener('scroll', this.scrollEvent)
    }
  },
  methods: {
    scrollEvent(){
      sessionStorage.setItem("personInformationScrollTopValue", this.$refs.personInformationScroll.scrollTop)
    },
    openPreview(){
      console.log("点击");
      this.$router.push({ name: 'PersonnalDataPriview' });
    },

    modifyHeadPhoto(){
      console.log("点击");
      this.$router.push({ name: 'ModifyHeadPhoto' , query: { userId: this.userInfo['userId'] }});
    },

    baseInformation(){
      this.$router.push({ name: 'BaseInformation' , query: { userId: this.userInfo['userId'] }});
    },
    editIntroduction(){
      this.$router.push({ name: 'EditIntroduction'});
    },

    editPartner(){
      this.$router.push({ name: 'EditPartner' });
    },

    editRomantic(){
      this.$router.push({ name: 'EditRomantic' });
    },

    requestUserInfo(){
      let that = this;
      Http.instance()
        .postJSON({
          url: "/makeFriends/sys/user/info",
          params: {
          },
        })
        .then((result) => {
          console.log("用户信息：" + JSON.stringify(result));
          if(result && result['user']){
            this.userInfo = result['user'];
            if(this.userInfo["headPicture"]){
              this.userInfo["headPictureUrl"] = new Uploader().formatImgPath(this.userInfo["headPicture"]);
            }else {
              this.userInfo["headPictureUrl"] = require('@/assets/icon/mine/cat.png');
            }
            if(this.userInfo["smilePicture"]){
              this.userInfo["smilePicture"] = new Uploader().formatImgPath(this.userInfo["smilePicture"]);
            }
            if(this.userInfo["lifePicture"]){
              this.userInfo["lifePicture"] = new Uploader().formatImgPath(this.userInfo["lifePicture"]);
            }
            if(this.userInfo["tripPicture"]){
              this.userInfo["tripPicture"] = new Uploader().formatImgPath(this.userInfo["tripPicture"]);
            }
            if(this.userInfo["seriousPicture"]){
              this.userInfo["seriousPicture"] = new Uploader().formatImgPath(this.userInfo["seriousPicture"]);
            }
            if(this.userInfo["talentPicture"]){
              this.userInfo["talentPicture"] = new Uploader().formatImgPath(this.userInfo["talentPicture"]);
            }
            if(this.userInfo["petPicture"]){
              this.userInfo["petPicture"] = new Uploader().formatImgPath(this.userInfo["petPicture"]);
            }
            if(this.userInfo['liveCity'] != null){
              this.userInfo['liveCityName'] = areaList['county_list'][this.userInfo['liveCity']];
            }
            if(this.userInfo['homeTown'] != null){
              this.userInfo['homeTownName'] = areaList['county_list'][this.userInfo['homeTown']];
            }
            if(this.userInfo['dataRate'] != null){
              var data = this.userInfo['dataRate'];
              // 1. 计算百分率数值（0.255再乘以100）
              const percentageValue = data* 100;
              // 1. 提取整数部分（向下取整，忽略小数）
              const integerPart = Math.floor(percentageValue); 
              this.userInfo['dataRate']  = integerPart;

            }
            if(this.userInfo['maritalStatus'] != null){
              var maritalStatus = this.userInfo['maritalStatus'];
              if(maritalStatus == MaritalStatusEnum.MARITAL_STATUS_UNMARRIED){
                this.userInfo['maritalStatusName'] = '未婚';
              }else if(maritalStatus == MaritalStatusEnum.MARITAL_STATUS_MARRIED){
                this.userInfo['maritalStatusName'] = '已婚';
              }else if(maritalStatus == MaritalStatusEnum.MARITAL_STATUS_DIVORCE){
                this.userInfo['maritalStatusName'] = '离异';
              }else if(maritalStatus == MaritalStatusEnum.MARITAL_STATUS_WIDOWED){
                this.userInfo['maritalStatusName'] = '丧偶';
              }
            }
            if(this.userInfo['workIndustry'] != null){
              this.userInfo['workIndustryCode'] = this.userInfo['workIndustry'];
              this.userInfo['workIndustryName'] = this.matchArrayName(WorkIndustryArray, this.userInfo['workIndustry']);
            }

          }
        }).catch((result) =>{
          console.log("错误信息：" + result);
          Notify({
            type: "danger",
            message: "" + result,
          });
        });
    },

    matchArrayName(arrayList, code){
      var name = "";
      if(arrayList != null){
        for(var i = 0; i < arrayList.length; i++){
          var item = arrayList[i];
          if(item['code'] == code){
            name = item['name'];
          }
        }
      }
      return name;
    },

    matchArrayIndex(arrayList, code){
      var index = 0;
      if(arrayList != null){
        for(var i = 0; i < arrayList.length; i++){
          var item = arrayList[i];
          if(item['code'] == code){
            index = i;
          }
        }
      }
      return index;
    },

    selectFile(type){
      console.log("点击选择文件, 类型：" + type );
      this.fileType = type;
      // this.acceptFile = "application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,text/plain";
      this.$refs.file.accept = "";
      this.$refs.file.click();
    },
    fileChange (e) {
      var files = this.$refs.file.files;
      console.log("回调");
      if(files && files.length > 0) {
         for (let i = 0; i < files.length; i++) {
          console.log("文件信息：" , files[i]);
          if(files[i].type.indexOf("image")!= -1)  {
            let fileObject = { fileName: files[i].name, file: files[i], fileId: `${new Date().getTime()}`, moduleName:'person', type:files[i].type};
            console.log("文件信息：" , this.acceptFile);
            new fileUploader().readFile(files[i], (base64) => {
              length++;
              fileObject.url = `${base64}`;
              this.uploadFile(fileObject);
            })
          }else {
            this.$toast.fail("请选择图片上传");
          }
        }
      }else {
        this.$toast.fail("请选择文件上传");
      }
    },

    
    uploadFile(fileObject) {
      var resultList = [];
      resultList.push({
        base64URL: fileObject['url'],
        moduleName: fileObject['moduleName'],
        fileName: fileObject['fileName'],
      });
      new Uploader().multiUpload(
        resultList,
        (urlArray) => {
          if(urlArray != null && urlArray.length == 1){
            this.submitUpdateMsg(urlArray[0]);
          }else {
            Notify({
              type: "danger",
              message: "图片上传失败，请联系平台或者稍候再试",
            });
          }
        },
        true,
        (error) => {
          console.log("错误信息：" + JSON.stringify(error));
          Notify({
            type: "danger",
            message: "图片上传失败，请联系平台或者稍候再试",
          });
        }
      );
    },

    submitUpdateMsg(picturePath){
      let that = this;
      var params = {
        userId:this.userInfo['userId'],
      };
      if(this.fileType == PictureEnum.HEAD){
        params['headPicture'] = picturePath;
      }else if(this.fileType == PictureEnum.SMILE){
        params['smilePicture'] = picturePath;
      }else if(this.fileType == PictureEnum.LIFE){
        params['lifePicture'] = picturePath;
      }else if(this.fileType == PictureEnum.TRIP){
        params['tripPicture'] = picturePath;
      }else if(this.fileType == PictureEnum.SERIOUS){
        params['seriousPicture'] = picturePath;
      }else if(this.fileType == PictureEnum.TALENT){
        params['talentPicture'] = picturePath;
      }else if(this.fileType == PictureEnum.PET){
        params['petPicture'] = picturePath;
      }
      Http.instance()
        .postJSON({
          url: "/makeFriends/sys/user/update",
          params: params,
        })
        .then((ret) => {
          // Notify({
          //     message: '上传成功',
          //     type: "success",
          // });
          if(this.fileType == PictureEnum.HEAD){
            this.$bus.$emit("refreshUserInfo", null);
          }else {
            this.requestUserInfo();
          }
        }).catch((result) =>{
          Notify({
            type: "danger",
            message: "" + result,
          });
        });
    },

    deleteFile(pictureType){
      this.$dialog
        .confirm({
          title: "确认",
          message: "您是否要确认删除该图片?",
        })
        .then(() => {
          console.log("点击确定");
          this.submitDelete(pictureType);
        })
        .catch(() => {
          // 点击取消或关闭事件
          console.log("点击取消或关闭");
        });
    },

    submitDelete(pictureType){
      var params = {
        'pictureType': pictureType,
      };
      Http.instance()
        .postJSON({
          url: "/makeFriends/sys/user/deleteUserPicture",
          params: params,
        })
        .then((ret) => {
          Notify({
            message: '删除成功',
            type: "success",
          });
          this.requestUserInfo();
        }).catch((result) =>{
          Notify({
            type: "danger",
            message: "" + result,
          });
        });
    },

    showPicture(pictureUrl){
      ImagePreview({
        images: [pictureUrl],
        startPosition: 0,
        onClose() {
          // do something
        }
      });
    },

    

    


    

    
    





  },
};
</script>

<style lang="less" scoped>
  .layoutVerticle{
    display: flex;
    flex-direction: column;
  }

  .layoutHorizontal{
    display: flex;
    flex-direction: row;
  }

  .layoutCenter{
    justify-content: center;
    align-items: center;
  }
  .verticleCenter {
    align-items: center;
  }

  

  .layoutPersonPhoto{
    // flex: 1;
    // height: 100px;
    height: calc((100vw - 64px) / 3);
    width: calc((100vw - 64px) / 3);
    position: relative;
  }
  .layoutPersonDiv{
    background:#f5f6f9;
    border-radius: 10px;
  }

  .imgPersonPhoto{
    height: calc((100vw - 64px) / 3);
    width: calc((100vw - 64px) / 3);
    border-radius: 10px;
    position: absolute;
  }

  .imgDelete{
    height: 20px;
    position: absolute;
    right: 10px;
    top: 10px;
  }



  .spanPersonPhoto{
    color: #3676F5; 
    margin-top: 6px;
  }

  .shapeWhiteRadio{
    margin-top: 12px;
    background: white;  
    padding: 10px; 
    border-radius: 10px;
  }

  .spanItemTitle{
    color: #9296a2;
    font-size: 16px;
    flex: 1;
  }
  .spanEdit{
    border: 1px solid #f5f6f9;
    color: #7a7f88;
    background: #f5f6f9;
    padding: 3px 6px;
    border-radius: 25px;
  }

  .layoutItemText{
    margin-top:6px
  }

  /deep/.van-cell {
    padding: 10px 0px;
  }

  .layoutHead{
    background: url("~@/assets/icon/home/person.webp") no-repeat;
    background-size: cover;
  }










</style>